package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Spot;
import cn.wolfcode.wolf2w.query.SpotQuery;
import cn.wolfcode.wolf2w.repository.SpotRepository;
import cn.wolfcode.wolf2w.service.ISpotService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
/**
* 景点服务接口实现
*/
@Service
//@Transactional  现在写不能事务, 需要讲完复制集才能使用事务
public class SpotServiceImpl implements ISpotService {

    @Autowired
    private SpotRepository repsitory;

    @Autowired
    private MongoTemplate template;



    @Override
    public void save(Spot spot) {
        spot.setId(null);
        repsitory.save(spot);
    }

    @Override
    public void update(Spot spot) {
        repsitory.save(spot);
    }

    @Override
    public void delete(String id) {
        repsitory.deleteById(id);
    }

    @Override
    public Spot get(String id) {
        return repsitory.findById(id).orElse(null);
    }

    @Override
    public List<Spot> list() {
        return repsitory.findAll();
    }

    @Override
    public Page<Spot> query(SpotQuery qo) {
        Query query = new Query();
        Pageable pageable = PageRequest.of(qo.getCurrentPage()- 1,qo.getPageSize(), Sort.Direction.ASC, "_id");
        return DBHelper.query(template,pageable, query,Spot.class, qo);
    }

    @Override
    public void saveOrUpdate(Spot spot) {
        if(StringUtils.hasLength(spot.getId())){
            //update
            this.update(spot);
        }else{
            //save
            this.save(spot);
        }
    }
}
